/**
 * 切面类
 *
 * @project sky-take-out_1
 * @author MECHREVO
 * @date 2023/12/5 09:37:34
 * @version 1.0
 */
package com.sky.aop;

import com.sky.annotation.AotuFillInsert;
import com.sky.annotation.AotuFillUpdate;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Objects;

@Component
@Aspect
@Slf4j
public class AotuFillAop {

    @Pointcut("@annotation(com.sky.annotation.AotuFillInsert)||" +
            "@annotation(com.sky.annotation.AotuFillUpdate)")
    public void pt(){}

    @Before("pt()")
    public void AotuFill(JoinPoint joinPoint){
        log.info("======拦截到了=======");
        //获取到当前被拦截的方法上的数据库操作类型
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();//获取方法签名对象
        //Method method = signature.getMethod();
        AotuFillInsert aotuFillInsert = signature.getMethod().getAnnotation(AotuFillInsert.class);//获取方法上注解对象
        AotuFillUpdate aotuFillUpdate = signature.getMethod().getAnnotation(AotuFillUpdate.class);//获取方法上注解对象
        try {
            if(Objects.nonNull(aotuFillInsert)){
                Object[] args = joinPoint.getArgs();
                Object param= args[0];
                Class<?> clazz = param.getClass();
                Method setCreateTime = clazz.getMethod("setCreateTime", LocalDateTime.class);
                Method setUpdateTime = clazz.getMethod("setUpdateTime", LocalDateTime.class);
                Method setCreateUser = clazz.getMethod("setCreateUser", Long.class);
                Method setUpdateUser = clazz.getMethod("setUpdateUser", Long.class);
                setCreateTime.invoke(param,LocalDateTime.now());
                setUpdateTime.invoke(param,LocalDateTime.now());
                setCreateUser.invoke(param, BaseContext.getCurrentId());
                setUpdateUser.invoke(param,BaseContext.getCurrentId());
            }
            if(Objects.nonNull(aotuFillUpdate)){
                Object[] args = joinPoint.getArgs();
                Object param= args[0];
                Class<?> clazz = param.getClass();
                Method setUpdateTime = clazz.getMethod("setUpdateTime", LocalDateTime.class);
                Method setUpdateUser = clazz.getMethod("setUpdateUser", Long.class);
                setUpdateTime.invoke(param,LocalDateTime.now());
                setUpdateUser.invoke(param,BaseContext.getCurrentId());
            }
        } catch (Exception e) {
           log.error("自动填充异常",e);
        }
    }
}
